﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using WebKit;
using WebKit.DOM;
using WindowService;

namespace CBrowser
{

    [StructLayout(LayoutKind.Sequential)]
    public struct POINTAPI
    {
        public int x;
        public int y;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MSG
    {
        public IntPtr hwnd;
        public int message;
        public long wParam;
        public long lParam;
        public int time;
        public POINTAPI pt;
    }
    public enum MessageType
    {
        UPGRADE_MESSAGE = 0,
        WARNING_MESSAGE = 2,
        LINK_STATE_MESSAGE = 4
    }

    public partial class CBrowser : Form
    {

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int RegisterWindowMessage(string lpString);

        public int linkStateMessageId = 0;
        private string currentDirectory = Directory.GetCurrentDirectory();
        private string baseUrl = null;
        private string failurePath = null;

        WebKitBrowser browser = null;
        protected Ini ini = null;
        public CBrowser()
        {
            InitializeComponent();
            ini = new Ini(currentDirectory, @"\\config.ini", this.getDefaultConfigIniContent());
            string logSavePath = getLogSavePath();
            Log.SavePath = logSavePath == "" ? currentDirectory : logSavePath;
            Log.needTrace = getShowTrace();
            Log.WriteLog("CBrowser Start application", LogType.Info);
            if (!this.getShowTrace())
            {
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                this.TopMost = true; 
            }
            
        }

        private void CBrowser_Load(object sender, EventArgs e)
        {
            linkStateMessageId = RegisterWindowMessage(MessageType.LINK_STATE_MESSAGE.ToString());

            RegisterMessages();
            browser = new WebKitBrowser();
            browser.Dock = DockStyle.Fill;
            browser.AllowNewWindows = false;
            browser.AllowDownloads = false;
            //禁用鼠标右键
            browser.IsWebBrowserContextMenuEnabled = false;
            this.Controls.Add(browser);

            this.navigate(this.getBaseUrl());
        }

        protected void RegisterMessages()
        {
            linkStateMessageId = RegisterWindowMessage(MessageType.LINK_STATE_MESSAGE.ToString());
            Log.WriteLog("CBrowser Register Windows Message, MessageId:" + linkStateMessageId.ToString(), LogType.Info);
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == linkStateMessageId)
            {
                Log.WriteLog("CBrowser Receive Windows Message: " + MessageType.LINK_STATE_MESSAGE + " wParam:" + m.WParam.ToString() + " lParam:" + m.LParam.ToString(), LogType.Info);
                if (m.WParam.ToString() == "0")
                {
                    navigate(this.getFailurePath());
                }
                else
                {
                    navigate(this.getBaseUrl());
                }
            }
            base.WndProc(ref m);
        }
        private void navigate(string url)
        {
            Log.WriteLog("CBrowser Browser ready to navigate: " + url, LogType.Trace);
            browser.Navigate(url);
            Log.WriteLog("CBrowser Browser Navigate to: " + url, LogType.Info);
        }
        //获取默认配置信息
        protected string getDefaultConfigIniContent()
        {
            return ";浏览器相关配置\r\n\r\n[Setting]"
                + "\r\n;是否开启调试日志\r\nShowTrace=true"
                + "\r\n\r\n;日志保存地址(默认:" + currentDirectory + ")\r\nLogSavePath=" + currentDirectory
                + "\r\n;正常服务的URL地址(http://wwww.baidu.com/)\r\nBaseUrl=http://wwww.baidu.com/"
                + "\r\n;断网页物理路径（C:\\yunding_window_services\\YunDingMonitors\\CBrowser\\bin\\Debug\\failure.html）\r\nFailurePath=" + currentDirectory + "/failure.html\r\n";
        }

        //开启调试日志
        private bool getShowTrace()
        {
            return ini.getStrConfig("Setting", "ShowTrace", "true") == "true" ? true : false;
        }
        //日志保存位置
        private string getLogSavePath()
        {
            return this.ini.getStrConfig("Setting", "LogSavePath");
        }
        //正常服务的URL地址
        private string getBaseUrl()
        {
            if (baseUrl == null) baseUrl = ini.getStrConfig("Setting", "BaseUrl");
            return baseUrl;
        }
        //断网页物理路径
        private string getFailurePath()
        {
            if (failurePath == null)
            {
                failurePath = ini.getStrConfig("Setting", "FailurePath");
                failurePath = new Uri(failurePath, UriKind.Absolute).AbsoluteUri;
            
            }
            return failurePath;
        }
        //图片缓存默认大小(0-65535 M)
        private int getCacheSize()
        {
            return ini.getIntConfig("Setting", "CacheSize", 0, 65535, 500);
        }
        //图片缓存路径
        private string getCachePath()
        {
            return ini.getStrConfig("Setting", "CachePath");
        }
        
    }
}

